import React, { useState,useEffect } from 'react'
import { MemberEntity } from '../model/member'
import { getMemberCollection } from '../api/memberApi'

const useMemberCollection=()=>{
    const [memberCollection,setMemberCollection]=useState<MemberEntity[]>([])
    const loadMemberCollection=()=>{
        getMemberCollection()
            .then(memberCollection=>setMemberCollection(memberCollection))
    }
    return{
        memberCollection,loadMemberCollection
    }
}

const MemberTableComponent: React.FC<{}> = () => {
    // 自定义hook
    const {memberCollection,loadMemberCollection}=useMemberCollection();
    useEffect(()=>{
        loadMemberCollection();
    },[])
    return (
        <div>
            <table>
                <thead>
                    <tr>
                        <th>Avatar</th>
                        <th>ID</th>
                        <th>Name</th>
                    </tr>
                </thead>
                <tbody>
                    {
                        memberCollection.map(member=>(
                            <MemberRow key={member.id} member={member}/>
                        ))
                    }
                </tbody>
            </table>
        </div>
    )
}

const MemberRow=({member}:{member:MemberEntity})=>{
    return(
        <tr>
            <td>
                <img src={member.avatar_url} style={{maxWidth:"10rem"}}/>
            </td>
            <td>
                <span>{member.id}</span>
            </td>
            <td>
                <span>{member.login}</span>
            </td>
        </tr>
    )
}
export default MemberTableComponent
